#-*-coding:utf-8-*-
'''
Created on 2011-9-3
@contact: 
@author: Administrator
'''
from db.settings import get_setting
from meta import DBSession
from utils.utility import coderule
class BaseModel(object):
    __Model__=object
    
    def get_code_setting(self,setting):
        """
                    获取编码规则，如果自动编码返回AUTO 
        @param setting: 编码规则
        @return: 编码规则        
        """
        return get_setting(setting)
    def check_code_rule(self,code):
        return coderule(code)
    def check_code_only(self,code):
        cl_code=self.__Model__.columntype['code']
        cd="%s='%s'" %(cl_code,code)
        return DBSession.query(self.__Model__).filter(cd).count()
    def get_by_code(self,code):
        cl_code=self.__Model__.columntype['code']
        cd="%s='%s'" %(cl_code,id)
        return DBSession.query(self.__Model__).filter(cd).first()
    def get_by_id(self,id):
        cl_id=self.__Model__.columntype['id']
        cd='%s=%s' %(cl_id,id)
        return DBSession.query(self.__Model__).filter(cd).first() 
    def check_active(self,code):
        pass
    def check_used(self,code):
        pass    
    def add(self,**attr):
        """
        @attention:增加用户组
        @param code:用户组代码
        @param name:用户组名称
        @return: True or False。   
        """
        m=self.__Model__()
        status=True
        for k,v in  attr.items():
            setattr(m,k,v)
            print m
        try:            
            DBSession.add(m)
            DBSession.commit()
            DBSession.flush()
            status=True
        except Exception,e:
            status=False
            print Exception,e
            DBSession.rollback()
            raise
        return status

    def edit(self,id,**attr):
        """
              编辑用户组信息
        @param id:用户组id 
        @param code:要更新的用户组代码
        @param name:要更新的用户组名称  
        """
        status=True
        colid=self.__Model__.columntype['id']
        cd="%s='%s'" %(colid,id)        
        print cd
        
        try:
            edit_co=DBSession.query(self.__Model__).filter(cd).first()
            for k,v in  attr.items():
                setattr(edit_co,k,v)
                #edit_co=attribute[key]               
            DBSession.commit()
            DBSession.flush()
            status=True
        except Exception,e:
            status=False
            DBSession.rollback()
            print Exception,e
            raise
        return status
    def delete(self,id):
        """
        @param group_id:  
        """
        status=True
        colid=self.__Model__.columntype['id']    
        try:            
            cd='%s=%s' %(colid,id)
            del_M=DBSession.query(self.__Model__).filter(cd).first()
            DBSession.delete(del_M)
            DBSession.commit()
            DBSession.flush()
            status= True
        except Exception,e:
            status=False
            DBSession.rollback()
            print Exception,e            
            raise
        return status
class TreeModel(BaseModel):
    def check_parent_code(self,code):
        pass
    def get_parent_by_id(self,id):
        pass
    def __get_parent_code__(self,chcode):
        pass
    def get_parent_by_code(self,code):
        cl_code=self.__Model__.columntype['code']
        cd="%s='%s'" %(cl_code,code)
        return DBSession.query(self.__Model__).filter(cd).count()
    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent

    def append(self, nodename):
        self.children[nodename] = TreeModel(nodename, parent=self)
    def update_fullname(self,id,name):
        pass
#    def check_code(self,code):
#        if 不符合编码规则:
#            pass
#        elif 编码重复:
#            pass
#        elif 上级不存在:
#            pass
#        elif 上级停用:
#            pass
#        else:
#            添加
    def __repr__(self):
        return "TreeNode(name=%r, id=%r, parent_id=%r)" % (
                    self.name,
                    self.id,
                    self.parent_id
                )
        
def dump_tree(node, indent=0):
    a=['<li>','</li>']
    b=['<li><ul>','</ul></li>']
    #判断是否末级，如果非末级就join b 否则a
    return "   " * indent + repr(node).join(a) + \
                "\n" + \
                "".join([
                    dump_tree(c, indent +1) 
                    for c in node.children.values()]
                )

